<?php


namespace app\service\order;


use app\common\exception\ApiException;
use app\model\coach\UserCoachModel;
use app\model\school\SchoolOrderModel;
use app\service\BaseService;
use app\service\user\CoachMoneyDetailService;

class SchoolOrderService extends BaseService
{

    public function __construct()
    {
        $this->model = new SchoolOrderModel();
    }

    /**
     * 完成订单
     * @param $id
     * @return bool
     * @throws ApiException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function completeOrderService($id)
    {
        $orderInfo = SchoolOrderModel::lock(true)->find($id);
        if (!$orderInfo) {
            throw new ApiException('订单不存在');
        }
        if ($orderInfo['status'] != SchoolOrderModel::ORDER_STUDYING) {
            throw new ApiException('订单状态错误');
        }
        $orderInfo->status = SchoolOrderModel::ORDER_COMPLETE;
        $orderInfo->complete_time = time();
        $orderInfo->save();

        // 结算教练工资
        $amount = $orderInfo['coach_amount'];
        $userCoachId = $orderInfo['accept_uid'];

        $coachMoneyDetailService = new CoachMoneyDetailService();
        $type = CoachMoneyDetailService::SALARY;
        $title = $coachMoneyDetailService->getTypeText($type);
        $coachMoneyDetailService->createLog($title, $userCoachId, $type, $amount, 0, $orderInfo['order_sn']);
        return true;
    }
}